<template>
  <div class="avg-month">
    <h4>{{ msgs }}</h4>
    <div ref="avgChart" class="avgChart"></div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import { getAvgMonthData } from "@/api/echartApi";
export default {
  name: "HelloWorld",
  props: {
    msgs: {
      type: String,
      default: '月平均电流及利用率'
    },
    type: {
      type: String,
      default: "AH1_IPA",
    },
    value: {
      type: String,
      default: 202.1,
    },
    month: {
      type: Array,
      default: () => {
        return []
      }
    },
    current: {
      type: String,
      default: "202.1A",
    },
    max: {
      type: String,
      default: 202.1,
    },
    avgData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null,
      powerData: [],
      timer: null,
      flag: true,
      i: 0,
      interval: 200,
      dates: 1,
      avg: 0,
      value2: [],
      monthData: ['01','02','03','04','05','06','07','08','09','10','11','12'],
      valueData: [86,26,45,63,82,26,74,22,10,44,56,90]
    };
  },
  watch: {
    // type: {
    //   handler(newVal) {
    //     console.log(newVal);
    //     //   this.fetchPowerData(newVal);
    //     this.getAvgMonth(newVal);
    //   },
    // },
    month: {
      handler(newval) {
        this.updateChart(newval)
      }
    }
  },
  mounted() {
    this.powerData = [];
    this.initChart();
    // this.fetchPowerData(this.type);
    // Update chart every 5 minutes
    this.timer = setInterval(() => {}, 300000);
    this.resizeHandler = () => {
      this.adjustChartSize(); // Call adjustChartSize on resize
    };
    window.addEventListener("resize", this.resizeHandler);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    isMobile() {
      // Basic check using userAgent or window width
      if (
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent
        )
      ) {
        return true;
      }
      return false; // Default to desktop
    },
    adjustChartSize() {
      if (!this.$refs.chartContainer) return;
      const container = this.$refs.chartContainer;
      if (this.isMobile()) {
        // Set width for mobile (e.g., 100% of viewport width minus padding)
        container.style.width = "calc(100vw - 40px)"; // Adjust 40px based on parent padding
        container.style.height = "300px"; // Adjust height for mobile if needed
        console.log("手机浏览器");
        this.interval = 700;
      } else {
        // Set width for desktop (e.g., 100% of container)
        container.style.width = "100%";
        container.style.height = "500px"; // Original desktop height
        console.log("电脑浏览器");
        this.interval = 200;
      }
      // Resize the ECharts instance
      if (this.chart) {
        this.chart.resize();
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.avgChart);
      this.adjustChartSize(); // Call adjustChartSize on init
      this.updateChart([]);
    },
    async fetchPowerData(name) {
      const res = await getAllPower(name);
      console.log(res.data);
      const sum = res.data.reduce((total, item, index) => {
        return total + item.DATA;
      }, 0);
      const avg = sum / res.data.length;
      console.log(avg, sum);
      this.powerData = res.data;
      this.updateChart(this.powerData);
    },
    async reFetchPowerData(name) {
      const res = await axios.get(`http://192.168.5.111:3000/api/one/${name}`);
      console.log(res.data[0].DATA);
      this.powerData.push(res.data[0]);
      this.updateChart(this.powerData);
    },
    // async getAvgMonth(name) {
    //   const res = await getAvgMonthData(name);
    //   // console.log(res);
    //   this.updateChart(res.data);
    // },
    updateChart(data) {
      // const concat = item => item.('CONCAT(RIGHT(date,6),CAST(hourF AS CHAR)'))
      // console.log(data);
      // const times = data.map((item) => ((item.date).slice(2)+-+item.HOURF+':'+item.MINUTEF)) || [];
      // const times = data.map((item) => item.month) || [];
      // const values =
      //   data.map((item) => (Math.trunc(item.avg_data * 10) / 10).toFixed(1)) ||
      //   [];
      // const value2 = data.map((item) =>
      //   ((Math.trunc(item.avg_data * 10) / 10 / this.max) * 100).toFixed(1)
      // );
      // this.value2 = value2;
      // console.log(value2);
      const option = {
        title: {
          // text: this.msg,
          textAlign: "left",
          left: "100px",
        },
        // tooltip: {
        //   show: false,
        //   trigger: "axis",
        //   //   formatter: "{b}<br />{a}: {c} A",
        // },
        grid: {
          right: "80%",
        },
        xAxis: {
          type: "category",
          data: this.month,
          boundaryGap: false,
          axisLabel: {
            //   interval: this.interval,
            //   rotate: 45,
            showMinLabel: true,
            showMaxLabel: true,
            fontWeight: 'bolder'
          },
        },
        yAxis: [
          {
            max: this.max,
            type: "value",
            name: "电流 (A)",
            position: "left",
            // interval: 20,
            axisLine: {
              show: true,
            },
            axisLabel: {
              show: true,
            },
          },
        ],
        series: [
          {
            name: "电流值(A)",
            type: "line",
            smooth: true,
            data: this.avgData,
            label: {
              show: true,
              position: "right",
              formatter: (params) => {
                const value = params.value;
                return (
                  `${params.value}` +
                  "(" +
                  ((value / this.value) * 100).toFixed(1) +
                  "%" +
                  ")"
                );
              },
              fontSize: 10,
              fontWeight: 'bolder'
            },
            markLine: {
              symbol: "none",
              data: [
                  {
                    yAxis: this.value,
                    name: "阈值A",
                    lineStyle: { color: "#f07d74", type: "solid", width: 3 },
                    label: {
                      show: true, // 显示标签
                      position: "middle", // 标签位置：'start'、'middle'、'end'
                      formatter: `额定电流: ${this.current}`, // {c} 自动替换为 yAxis 值
                    },
                  },
                //   {
                //     type: 'average',
                //     name: '平均电流',
                //     lineStyle: {color:'#ffcd43', type: 'solid'},
                //     label:{
                //       show: true,
                //       position: 'middle',
                //       formatter: 'A项平均电流: {c}'
                //     }
                //   }
              ],
            },
          },
          //   {
          //     name: "平均利用率(%)",
          //     type: "line",
          //     smooth: true,
          //     // yAxisIndex: 1,
          //     data: value2,
          //     label: {
          //       show: true,
          //       position: "right",
          //       formatter: '{c}%',
          //     },
          //   },
        ],
        //   dataZoom: [
        //     {
        //       type: "slider",
        //       show: true,
        //       start: 75,
        //       end: 100,
        //       bottom: 10,
        //       zoomLock: true,
        //       realtime: true,
        //       handleStyle: {
        //         // 隐藏滑块手柄
        //         color: "transparent",
        //         borderWidth: 0,
        //       },
        //       brushSelect: false,
        //       handleStyle: {
        //         color: "#666", // 默认手柄颜色
        //         borderColor: "#999", // 默认边框颜色
        //         borderWidth: 1, // 默认边框宽度
        //         // 鼠标悬停时的样式
        //         emphasis: {
        //           color: "#ff4500", // 悬停颜色（橙色）
        //           borderColor: "#ff4500", // 悬停边框颜色
        //           borderWidth: 2, // 悬停边框加粗
        //         },
        //       },
        //       moveHandleStyle: {
        //         color: "rgba(100,100,100,0.3)", // 默认移动条颜色
        //         // 鼠标悬停时的样式
        //         emphasis: {
        //           color: "rgba(100,100,100,0.5)", // 悬停颜色加深
        //         },
        //       },
        //     },
        //     {
        //       type: "inside",
        //       start: 75,
        //       end: 100,
        //       zoomLock: true,
        //       filterMode: "filter",
        //     },
        //   ],
        grid: {
          bottom: 30,
          left: 35,
            right: 70,
        },
      };

      this.chart.setOption(option);
      window.addEventListener("resize", () => {
        this.chart && this.chart.resize();
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.avg-month {
  width: 44vw;
  /* height: 25vh; */
  /* width: 60%; */
  height: 25vh;
  /* background-color: pink; */
  /* transform: translateY(-20%);
  transform: translateX(20%); */
}
h4 {
  box-sizing: border-box;
  transform: translate(25%, -110%);
}
.avgChart {
  width: 100%;
  height: 100%;
  transform: translateY(-40%);
}
@media (max-width: 1200px) {
  .avgChart {
    width: 100vw;
    height: 25vh;
  }
}
@media (max-width: 1200px) and (orientation: landscape) {
  h4 {
    transform: translate(25%, 180%);
  }
  .avg-month {
    width: 70vw;
    height: 50vh;
  }
  .avgChart {
    width: 100%;
    height: 100%;
    transform: translateY(5%);
  }
}
</style>
